package com.xm.share.controller;

import java.util.Collection;
import java.util.List;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.xm.share.model.vo.NoticeContentDetail;
import com.xm.share.model.vo.NoticeData;
import com.xm.share.service.PictureShareService;
import com.xm.share.service.SpringContextUtil;

@Controller
@RequestMapping("/system/noticeContent")
public class NoticeContentController extends BaseController {

	/**
	 * 进入NoticeContent服务列表页面
	 * 
	 * @return String 视图
	 * @throws Exception
	 *             异常
	 */
	@RequestMapping("/index")
	public String index() throws Exception {
		LOGGER.info("---------------进入NoticeContentController.index()-------------------");

		return "/system/noticeManager/noticeContentList";
	}

	/**
	 * dwr调用主页面的js来弹屏最新创建的公告
	 * 
	 * @param noticeContentDetail
	 *            添加成功的通知
	 * @throws Exception
	 *             异常
	 */
	public void sendTipMessage(final NoticeContentDetail noticeContentDetail) throws Exception {
		LOGGER.info("---------------进入NoticeContentController(dwr).sendTipMessage()-------------------");
		Runnable runable = new Runnable() {
			ScriptBuffer scriptBuffer = new ScriptBuffer();

			@Override
			public void run() {
				scriptBuffer.appendCall("showContent", noticeContentDetail); // 获取页面上的showContent的js函数并设置参数为noticeContentList
				Collection<ScriptSession> scriptSessions = Browser.getTargetSessions(); // 获取所有有showContent函数的页面的session
				for (ScriptSession scriptSessoin : scriptSessions) { // 遍历所有的页面，添加js脚本
					scriptSessoin.addScript(scriptBuffer);
				}
			}
		};
		Browser.withAllSessions(runable); // 执行推行消息
	}

	/**
	 * dwr调用主页面的js来弹屏最新创建的公告
	 * 
	 * @param userId
	 *            用户id
	 * @throws Exception
	 *             异常
	 */
	public void queryNoticeByUserId(final String userId) throws Exception {
		LOGGER.info("---------------进入NoticeContentController(dwr).queryNoticeByUserId()-------------------");
		PictureShareService pictureShareService = SpringContextUtil.getBean(PictureShareService.class);
		NoticeData datas = pictureShareService.queryTopMsgByuserId(userId);
		Gson gson = new Gson();
		final String json = gson.toJson(datas);
		Runnable runable = new Runnable() {
			ScriptBuffer scriptBuffer = new ScriptBuffer();

			@Override
			public void run() {
				scriptBuffer.appendCall("contentList", json); // 获取页面上的showContent的js函数并设置参数为noticeContentList
				Collection<ScriptSession> scriptSessions = Browser.getTargetSessions(); // 获取所有有showContent函数的页面的session
				for (ScriptSession scriptSessoin : scriptSessions) { // 遍历所有的页面，添加js脚本
					scriptSessoin.addScript(scriptBuffer);
				}
			}
		};
		Browser.withAllSessions(runable); // 执行推行消息
	}

}
